

#include "widget_funcc_smart_home.h"
#include "ui_widget_funcc_smart_home.h"

Widget_funcC_Smart_Home::Widget_funcC_Smart_Home(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcC_Smart_Home)
{
    ui->setupUi(this);
    
    // 创建网络服务管理对象
    this->network_manager = new QNetworkAccessManager();
    this->lyric_network_manager = new QNetworkAccessManager();
    this->search_network_manager = new QNetworkAccessManager();
    this->player = new QMediaPlayer();
    // 服务器收到数据后，与自定义槽函数相连
    connect(this->network_manager,&QNetworkAccessManager::finished,this,&Widget_funcC_Smart_Home::onReplied);
    connect(this->lyric_network_manager,&QNetworkAccessManager::finished,this,&Widget_funcC_Smart_Home::lyric_onReplied);
    connect(this->search_network_manager,&QNetworkAccessManager::finished,this,&Widget_funcC_Smart_Home::seach_onReplied);
    // 播放器信号链接
    connect(this->player, &QMediaPlayer::positionChanged, this, &Widget_funcC_Smart_Home::onPositionChanged);
    connect(this->player, &QMediaPlayer::mediaStatusChanged, this, &Widget_funcC_Smart_Home::onMediaStatusChanged);

    // 链接远程
    this->connect_tcp_serve();
    // 初始化组件
    this->init_module();

    // 默认播放热门歌单
    this->set_url(QUrl("https://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%E7%83%AD%E9%97%A8%E6%AD%8C%E6%9B%B2&type=1&offset=0&total=true&limit=10"));
    get_joson();

    // 初始化进度条
    this->init_music_bar();
}

Widget_funcC_Smart_Home::~Widget_funcC_Smart_Home()
{
    delete ui;
}

// 按钮互斥设置
void Widget_funcC_Smart_Home::slots_button_start(bool start)
{
    
    QObject * temp = sender();
    // 离开
    if(temp == ui->label_run_home)
    {
        // 离家开
        ui->label_run_home->set_start(start);
        // 归家关
        ui->label_return_home->set_start(!start);
        // 扫地机器人开
        ui->clean_robot_button->set_start(start);
        ui->clean_robot->setPixmap(QPixmap(":/扫地机开"));
        ui->run_home_1->setPixmap(QPixmap(":/扫地机开"));
        ui->clean_robot_button_text->setText("ON");
        // 窗帘开
        ui->curtain_button->set_start(start);
        ui->curtain->setPixmap(QPixmap(":/窗帘开"));
        ui->run_home_2->setPixmap(QPixmap(":/窗帘开"));
        ui->curtain_button_text->setText("ON");
        // 空调关
        ui->air_button->set_start(!start);
        ui->air->setPixmap(QPixmap(":/空调"));
        ui->return_home_1->setPixmap(QPixmap(":/空调"));
        ui->air_button_text->setText("OFF");
        // 灯关
        ui->light_button->set_start(!start);
        ui->light->setPixmap(QPixmap(":/灯"));
        ui->return_home_2->setPixmap(QPixmap(":/灯"));
        ui->light_button_text->setText("OFF");
        // 路由器关
        ui->router_button->set_start(!start);
        ui->router->setPixmap(QPixmap(":/路由器"));
        ui->return_home_3->setPixmap(QPixmap(":/路由器"));
        ui->router_button_text->setText("OFF");
        send_message("curtain opened\r\n");
        send_message("clean opened\r\n");
        send_message("air closed\r\n");
        send_message("light closed\r\n");
        send_message("router closed\r\n");
    }
    // 归家
    if(temp == ui->label_return_home)
    {
        // 离家关
        ui->label_return_home->set_start(start);
        // 归家开
        ui->label_run_home->set_start(!start);
        // 扫地机器人关
        ui->clean_robot_button->set_start(!start);
        ui->clean_robot->setPixmap(QPixmap(":/扫地机"));
        ui->run_home_1->setPixmap(QPixmap(":/扫地机"));
        ui->clean_robot_button_text->setText("OFF");
        // 窗帘关
        ui->curtain_button->set_start(!start);
        ui->curtain->setPixmap(QPixmap(":/窗帘"));
        ui->run_home_2->setPixmap(QPixmap(":/窗帘"));
        ui->curtain_button_text->setText("OFF");
        // 空调开
        ui->air_button->set_start(start);
        ui->air->setPixmap(QPixmap(":/空调开"));
        ui->return_home_1->setPixmap(QPixmap(":/空调开"));
        ui->air_button_text->setText("ON");
        // 灯开
        ui->light_button->set_start(start);
        ui->light->setPixmap(QPixmap(":/灯开"));
        ui->return_home_2->setPixmap(QPixmap(":/灯开"));
        ui->light_button_text->setText("ON");
        // 路由器开
        ui->router_button->set_start(start);
        ui->router->setPixmap(QPixmap(":/路由器开"));
        ui->return_home_3->setPixmap(QPixmap(":/路由器开"));
        ui->router_button_text->setText("ON");
        send_message("curtain closed\r\n");
        send_message("clean closed\r\n");
        send_message("air opened\r\n");
        send_message("light opened\r\n");
        send_message("router opened\r\n");
    }
    // 睡觉
    if (temp == ui->label_sleep)
    {
        // 睡觉开
        ui->label_sleep->set_start(start);
        // 归家关
        ui->label_getUp->set_start(!start);
        // 关灯
        ui->light_button->set_start(!start);
        ui->light->setPixmap(QPixmap(":/灯"));
        ui->getUp_1->setPixmap(QPixmap(":/灯"));
        ui->light_button_text->setText("OFF");
        // 关窗帘
        ui->curtain_button->set_start(!start);
        ui->curtain->setPixmap(QPixmap(":/窗帘"));
        ui->getUp_2->setPixmap(QPixmap(":/窗帘"));
        ui->curtain_button_text->setText("OFF");
        send_message("curtain closed\r\n");
        send_message("light closed\r\n");
    }
    // 起床
    if (temp == ui->label_getUp)
    {
        // 睡觉关
        ui->label_getUp->set_start(start);
        // 归家开
        ui->label_sleep->set_start(!start);
        // 开灯
        ui->light_button->set_start(start);
        ui->light->setPixmap(QPixmap(":/灯开"));
        ui->getUp_1->setPixmap(QPixmap(":/灯开"));
        ui->light_button_text->setText("NO");
        // 开窗帘
        ui->curtain_button->set_start(start);
        ui->curtain->setPixmap(QPixmap(":/窗帘开"));
        ui->getUp_2->setPixmap(QPixmap(":/窗帘开"));
        ui->curtain_button_text->setText("NO");
        send_message("curtain opened\r\n");
        send_message("light opened\r\n");
    }
    // 控制灯
    if (temp == ui->light_button)
    {
        if (start)
        {
            this->ui->light->setPixmap(QPixmap(":/灯开"));
            this->ui->light_button_text->setText("ON");
            send_message("light opened\r\n");
        }
        else
        {
            this->ui->light->setPixmap(QPixmap(":/灯"));
            this->ui->light_button_text->setText("OFF");
            send_message("light closed\r\n");
        }
    }
    // 控制冰箱
    if (temp == ui->fridge_button)
    {
        if (start)
        {
            this->ui->fridge->setPixmap(QPixmap(":/冰箱开"));
            this->ui->fridge_button_text->setText("ON");
            send_message("fridge opened\r\n");
        }
        else
        {
            this->ui->fridge->setPixmap(QPixmap(":/冰箱"));
            this->ui->fridge_button_text->setText("OFF");
            send_message("fridge closed\r\n");
        }
    }
    // 控制路由器
    if (temp == ui->router_button)
    {
        if (start)
        {
            this->ui->router->setPixmap(QPixmap(":/路由器开"));
            this->ui->router_button_text->setText("ON");
        }
        else
        {
            this->ui->router->setPixmap(QPixmap(":/路由器"));
            this->ui->router_button_text->setText("OFF");
        }
    }
    // 控制扫地机器人
    if (temp == ui->clean_robot_button)
    {
        if (start)
        {
            this->ui->clean_robot->setPixmap(QPixmap(":/扫地机开"));
            this->ui->clean_robot_button_text->setText("ON");
            send_message("clean opened\r\n");
        }
        else
        {
            this->ui->clean_robot->setPixmap(QPixmap(":/扫地机"));
            this->ui->clean_robot_button_text->setText("OFF");
            send_message("clean closed\r\n");
        }
    }
    // 控制空调
    if (temp == ui->air_button)
    {
        if (start)
        {
            this->ui->air->setPixmap(QPixmap(":/空调开"));
            this->ui->air_button_text->setText("ON");
            send_message("air opened\r\n");
        }
        else
        {
            this->ui->air->setPixmap(QPixmap(":/空调"));
            this->ui->air_button_text->setText("OFF");
            send_message("air closed\r\n");
        }
    }
    // 控制窗帘
    if (temp == ui->curtain_button)
    {
        if (start)
        {
            this->ui->curtain->setPixmap(QPixmap(":/窗帘开"));
            this->ui->curtain_button_text->setText("ON");
            send_message("curtain opened\r\n");
        }
        else
        {
            this->ui->curtain->setPixmap(QPixmap(":/窗帘"));
            this->ui->curtain_button_text->setText("OFF");
            send_message("curtain closed\r\n");
        }
    }
}

void Widget_funcC_Smart_Home::slots_button_send_message()
{
    // 增加一个widget  内部包含
    
}

// 连接服务端: 用于远程交互
void Widget_funcC_Smart_Home::connect_tcp_serve()
{

    // TCP客户端信号链接
    connect(&this->client, &Tcp_client::connect_sig, this, [&](){
        this->ui->tcp_connect_label->setText("远程链接成功");
    });
    connect(&this->client, &Tcp_client::dis_connect_sig, this, [&](){
        this->ui->tcp_connect_label->setText("远程链接失败");
        QMessageBox::warning(this,"提示","远程链接失败!", QMessageBox::Ok);
    });
    connect(&this->client, &Tcp_client::read_sig, this , [&](QString message){

         if (message == "play music")
         {
             this->begin_play();
         }
         else if (message == "stop music")
         {
             this->stop_play();
         }
         else if (message == "open air")
         {
             this->ui->air->setPixmap(QPixmap(":/空调开"));
             this->ui->air_button->setPixmap(QPixmap(":/状态按钮_开"));
             this->ui->air_button->set_start(true);
             this->ui->air_button_text->setText("ON");
         }
         else if (message == "close air")
         {
             this->ui->air->setPixmap(QPixmap(":/空调"));
             this->ui->air_button->setPixmap(QPixmap(":/状态按钮_关"));
             this->ui->air_button->set_start(false);
             this->ui->air_button_text->setText("OFF");
         }
         else if (message == "open router")
         {
             this->ui->router->setPixmap(QPixmap(":/路由器开"));
             this->ui->router_button->setPixmap(QPixmap(":/状态按钮_开"));
             this->ui->router_button->set_start(true);
             this->ui->router_button_text->setText("ON");
         }
         else if (message == "close router")
         {
             this->ui->router->setPixmap(QPixmap(":/路由器"));
             this->ui->router_button->setPixmap(QPixmap(":/状态按钮_关"));
             this->ui->router_button->set_start(false);
             this->ui->router_button_text->setText("OFF");
         }
         else if (message == "open fridge")
         {
             this->ui->fridge->setPixmap(QPixmap(":/冰箱开"));
             this->ui->fridge_button->setPixmap(QPixmap(":/状态按钮_开"));
             this->ui->fridge_button->set_start(true);
             this->ui->fridge_button_text->setText("ON");
         }
         else if (message == "close fridge")
         {
             this->ui->fridge->setPixmap(QPixmap(":/冰箱"));
             this->ui->fridge_button->setPixmap(QPixmap(":/状态按钮_关"));
             this->ui->fridge_button->set_start(false);
             this->ui->fridge_button_text->setText("OFF");
         }
         else if (message == "open curtain")
         {
             this->ui->curtain->setPixmap(QPixmap(":/窗帘开"));
             this->ui->curtain_button->setPixmap(QPixmap(":/状态按钮_开"));
             this->ui->curtain_button->set_start(true);
             this->ui->curtain_button_text->setText("ON");
         }
         else if (message == "close curtain")
         {
             this->ui->curtain->setPixmap(QPixmap(":/窗帘"));
             this->ui->curtain_button->setPixmap(QPixmap(":/状态按钮_关"));
             this->ui->curtain_button->set_start(false);
             this->ui->curtain_button_text->setText("OFF");
         }
         else if (message == "open light")
         {
             this->ui->light->setPixmap(QPixmap(":/灯开"));
             this->ui->light_button->setPixmap(QPixmap(":/状态按钮_开"));
             this->ui->light_button->set_start(true);
             this->ui->light_button_text->setText("ON");
         }
         else if (message == "close light")
         {
             this->ui->light->setPixmap(QPixmap(":/灯"));
             this->ui->light_button->setPixmap(QPixmap(":/状态按钮_关"));
             this->ui->light_button->set_start(false);
             this->ui->light_button_text->setText("OFF");
         }
         else if (message == "open clean")
         {
             this->ui->clean_robot->setPixmap(QPixmap(":/扫地机开"));
             this->ui->clean_robot_button->setPixmap(QPixmap(":/状态按钮_开"));
             this->ui->clean_robot_button->set_start(true);
             this->ui->clean_robot_button_text->setText("ON");
         }
         else if (message == "close clean")
         {
             this->ui->clean_robot->setPixmap(QPixmap(":/扫地机"));
             this->ui->clean_robot_button->setPixmap(QPixmap(":/状态按钮_关"));
             this->ui->clean_robot_button->set_start(false);
             this->ui->clean_robot_button_text->setText("OFF");
         }
    });
    this->client.set_Connect("192.168.50.133",2000);
    this->client.start_Connect();
}

// 获取歌曲数据
void Widget_funcC_Smart_Home::get_joson()
{
    this->network_manager->get(QNetworkRequest(this->song_url));
}

// 获取歌词数据
void Widget_funcC_Smart_Home::get_lyric_joson(void)
{

   QUrl cur_lyric_url;
   QStringList song_information_list = this->analysis_song_information(this->cur_index_song);
   if (song_information_list.isEmpty())
   {
       return;
   }
   QString url_string = QString("https://music.163.com/api/song/lyric?id=") + song_information_list.at(0) + QString("&lv=1&kv=1&tv=-1");
   cur_lyric_url = QUrl(url_string);
   this->lyric_network_manager->get(QNetworkRequest(cur_lyric_url));
}

// 获取搜索歌曲数据
void Widget_funcC_Smart_Home::get_search_json()
{
    this->search_network_manager->get(QNetworkRequest(this->song_url));
}

// 设置JSON数据入口
void Widget_funcC_Smart_Home::set_url(QUrl url)
{
    this->song_url = url;
}

// 解析JSON数据
void Widget_funcC_Smart_Home::analysis_joson()
{
    this->song_information.clear();
    QFile file("./song.json");
    file.open(QFile::ReadOnly);
    QByteArray json_byte = file.readAll();
    file.close();

    QJsonDocument json_doc = QJsonDocument::fromJson(json_byte);
    if (!json_doc.isObject())
    {
        qDebug() << "doc is not a object";
        QMessageBox::warning(this,"提示","解析数据失败!", QMessageBox::Ok);
        return;
    }

    QJsonObject json_obj = json_doc.object();
    QStringList keys = json_obj.keys();

    for (int i = 0; i < keys.size();i++)
    {
        if (keys.at(i) == "result")
        {
            QJsonObject result_value_obj = json_obj.value(keys.at(i)).toObject();
            QStringList result_keys = result_value_obj.keys();
            for (int j = 0; j < result_keys.size(); j++)
            {
                if (result_keys.at(j) == "songs")
                {
                    QJsonArray songs_value_arr = result_value_obj.value(result_keys.at(j)).toArray();
                    for (int k = 0; k < songs_value_arr.size(); k++)
                    {
                        QJsonObject song_value_obj = songs_value_arr[k].toObject();
                        QStringList song_value_keys = song_value_obj.keys();
                        for (int n = 0; n < song_value_keys.size(); n++)
                        {
                            if (song_value_keys.at(n) == "id")
                            {

                                this->song_id = QString::number(song_value_obj.value(song_value_keys.at(n)).toInt());
                                qDebug() << "song_id: " << song_id;
                            }

                            if (song_value_keys.at(n) == "name")
                            {
                                this->song_name = song_value_obj.value(song_value_keys.at(n)).toString();
                                qDebug() << "song_name: " << song_name;
                            }

                            if (song_value_keys.at(n) == "artists")
                            {
                                QJsonArray artists_value_arr = song_value_obj.value(song_value_keys.at(n)).toArray();
                                QJsonObject artists_obj = artists_value_arr.at(0).toObject();
                                QStringList artists_obj_keys = artists_obj.keys();
                                for (int f = 0; f < artists_obj_keys.size(); f++)
                                {
                                    if (artists_obj_keys.at(f) == "name")
                                    {
                                        this->singer_name = artists_obj.value(artists_obj_keys.at(f)).toString();
                                        qDebug() << "singer_name: " << singer_name;
                                        break;
                                    }
                                }
                            }
                        }
                        QString general_message = this->song_id + QString("&") + this->song_name + QString("&") + this->singer_name;
                        this->song_information.append(general_message);
                    }
                }
            }
        }
    }

}

// 解析歌词JSON数据
void Widget_funcC_Smart_Home::analysis_lyric_joson(void)
{
    // 首先把之前的数据清空
    this->cur_posi_list.clear();
    this->cur_lyric_list.clear();
    this->cur_posi_lyric_list.clear();

    QFile file("./lyric.json");
    file.open(QFile::ReadOnly);
    QByteArray json_byte = file.readAll();
    file.close();

    QJsonDocument json_doc = QJsonDocument::fromJson(json_byte);

    if (!json_doc.isObject())
    {
        qDebug() << "doc is not a object";
        QMessageBox::warning(this,"提示","解析数据失败!", QMessageBox::Ok);
        return;
    }

    QJsonObject json_obj = json_doc.object();
    QStringList keys = json_obj.keys();

    for (int i = 0; i < keys.size(); i++)
    {
        if (keys.at(i) == "lrc")
        {
            QJsonObject lrc_value_obj = json_obj.value(keys.at(i)).toObject();
            QStringList lrc_value_keys = lrc_value_obj.keys();
            for (int j = 0; j < lrc_value_keys.size(); j++)
            {
                if (lrc_value_keys.at(j) == "lyric")
                {
                    this->cur_lyric = lrc_value_obj.value(lrc_value_keys.at(j)).toString();
                    qDebug() << "cur_lyric: " << this->cur_lyric;
                    QStringList cur_lyric_list = cur_lyric.split("\n");
                    for (int k = 0; k < cur_lyric_list.size(); k++)
                    {
                        if (cur_lyric_list.at(k) == "")
                        {
                            continue;
                        }
                        int minute = 0;
                        int millisecond = 0;
                        int second = 0;
                        QString temp = cur_lyric_list.at(k);
                        QStringList temp_list = temp.split("]");

                        std::sscanf(temp_list.at(0).toUtf8(),"[%d:%d.%d", &minute,&second,&millisecond);
                        int positon = minute * 60 * 1000 + second * 1000 + millisecond;
                        QString pos_lyric = temp_list.at(1);
                        this->cur_posi_list.append(QString::number(positon));
                        this->cur_lyric_list.append(pos_lyric);
                        this->cur_posi_lyric_list.append(QString::number(positon) + QString("&") + pos_lyric);
                        qDebug() << "cur_posi_lyric: " << this->cur_posi_lyric_list.at(k);
                    }
                    break;
                }
            }
        }
    }
    this->ui->song_text->setText(cur_posi_lyric_list.at(0).split("&").at(1));
}

// 解析搜索数据
void Widget_funcC_Smart_Home::analysis_search_joson()
{
    QFile file("./search.json");
    file.open(QFile::ReadOnly);
    QByteArray json_byte = file.readAll();
    file.close();

    QJsonDocument json_doc = QJsonDocument::fromJson(json_byte);
    if (!json_doc.isObject())
    {
        qDebug() << "doc is not a object";
        QMessageBox::warning(this,"提示","解析数据失败!", QMessageBox::Ok);
        return;
    }

    QJsonObject json_obj = json_doc.object();
    QStringList keys = json_obj.keys();

    for (int i = 0; i < keys.size();i++)
    {
        if (keys.at(i) == "result")
        {
            QJsonObject result_value_obj = json_obj.value(keys.at(i)).toObject();
            QStringList result_keys = result_value_obj.keys();
            for (int j = 0; j < result_keys.size(); j++)
            {
                if (result_keys.at(j) == "songs")
                {
                    QJsonArray songs_value_arr = result_value_obj.value(result_keys.at(j)).toArray();
                    QJsonObject song_value_obj = songs_value_arr[0].toObject(); // 第一首歌

                    if (song_value_obj.contains("id"))  // 先判断字段是否存在
                    {
                        this->song_id = QString::number(song_value_obj["id"].toVariant().toLongLong());
                        qDebug() << "直接解析的 song_id: " << song_id;
                    }
                    else
                    {
                        qDebug() << "歌曲数据中无 id 字段";
                        this->song_id = "0";
                    }

                    // 2. 直接获取 name（同理）
                    if (song_value_obj.contains("name"))
                    {
                        this->song_name = song_value_obj["name"].toString();
                        qDebug() << "song_name: " << song_name;
                    }

                    // 3. 直接获取 artists（同理）
                    if (song_value_obj.contains("artists"))
                    {
                        QJsonArray artists_value_arr = song_value_obj["artists"].toArray();
                        if (!artists_value_arr.isEmpty())
                        {
                            QJsonObject artists_obj = artists_value_arr[0].toObject();
                            if (artists_obj.contains("name"))
                            {
                                this->singer_name = artists_obj["name"].toString();
                                qDebug() << "singer_name: " << singer_name;
                            }
                        }
                    }

                    QString general_message = this->song_id + QString("&") + this->song_name + QString("&") + this->singer_name;
                    this->song_information.append(general_message);
                    QString cur_song_url = QString("http://music.163.com/song/media/outer/url?id=") + this->song_id + QString(".mp3");
                    this->playlist.addMedia(QMediaContent(QUrl(cur_song_url)));
                    // 关键修改：设置当前索引为0（新添加的歌曲）
                    this->playlist.setCurrentIndex(0);
                    this->cur_index_song = 0;
                    this->player->setPlaylist(&this->playlist);

                    // 延迟播放，给资源加载留时间
                    QTimer::singleShot(200, this, [=]() {
                        ui->play->setPixmap(QPixmap(":/播放"));
                        ui->play->set_start(true);
                        player->play();
                    });
                    break;
                }

            }
        }
    }
}

// 初始化组件
void Widget_funcC_Smart_Home::init_module()
{

    this->initGif();
    ui->sleep_home_label->setPixmap(QPixmap(":/卧室"));
    ui->label_return_home->setPixmap(QPixmap(":/状态按钮_关"));
    ui->label_run_home->setPixmap(QPixmap(":/状态按钮_关"));
    ui->label_sleep->setPixmap(QPixmap(":/状态按钮_关"));
    ui->label_getUp->setPixmap(QPixmap(":/状态按钮_关"));
    ui->air_button->setPixmap(QPixmap(":/状态按钮_关"));
    ui->fridge_button->setPixmap(QPixmap(":/状态按钮_关"));
    ui->light_button->setPixmap(QPixmap(":/状态按钮_关"));
    ui->router_button->setPixmap(QPixmap(":/状态按钮_关"));
    ui->curtain_button->setPixmap(QPixmap(":/状态按钮_关"));
    ui->clean_robot_button->setPixmap(QPixmap(":/状态按钮_关"));
    ui->run_home_1->setPixmap(QPixmap(":/扫地机"));
    ui->run_home_2->setPixmap(QPixmap(":/窗帘"));
    ui->return_home_1->setPixmap(QPixmap(":/空调"));
    ui->return_home_2->setPixmap(QPixmap(":/灯"));
    ui->return_home_3->setPixmap(QPixmap(":/路由器"));
    ui->sleep_1->setPixmap(QPixmap(":/灯"));
    ui->sleep_2->setPixmap(QPixmap(":/窗帘"));
    ui->getUp_1->setPixmap(QPixmap(":/灯"));
    ui->getUp_2->setPixmap(QPixmap(":/窗帘"));

    ui->return_home_text->setText("回家");
    ui->run_home_text->setText("离家");
    ui->sleep_text->setText("睡觉");
    ui->getUp_text->setText("起床");
    ui->air_text->setText("空调");
    ui->light_text->setText("灯");
    ui->fridge_text->setText("冰箱");
    ui->router_text->setText("路由器");
    ui->curtain_text->setText("窗帘");
    ui->clean_robot_text->setText("扫地机");
    ui->clean_robot_button_text->setText("OFF");
    ui->light_button_text->setText("OFF");
    ui->fridge_button_text->setText("OFF");
    ui->curtain_button_text->setText("OFF");
    ui->air_button_text->setText("OFF");
    ui->router_button_text->setText("OFF");

    ui->light->setPixmap(QPixmap(":/灯"));
    ui->light->setScaledContents(true);
    ui->router->setPixmap(QPixmap(":/路由器"));
    ui->router->setScaledContents(true);
    ui->clean_robot->setPixmap(QPixmap(":/扫地机"));
    ui->clean_robot->setScaledContents(true);
    ui->curtain->setPixmap(QPixmap(":/窗帘"));
    ui->curtain->setScaledContents(true);
    ui->fridge->setPixmap(QPixmap(":/冰箱"));
    ui->fridge->setScaledContents(true);
    ui->air->setPixmap(QPixmap(":/空调"));
    ui->air->setScaledContents(true);
    ui->play->setPixmap(QPixmap(":/停止"));
    ui->play->setScaledContents(true);
    ui->last_song->setPixmap(QPixmap(":/上一首"));
    ui->last_song->setScaledContents(true);
    ui->next_song->setPixmap(QPixmap(":/下一首"));
    ui->next_song->setScaledContents(true);
    ui->music_label->setPixmap(QPixmap(":/音乐"));
    ui->music_label->setScaledContents(true);

    // 连接按钮信号
    connect(ui->label_return_home , &Button_home_start::signals_start , this , &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->label_run_home , &Button_home_start::signals_start , this , &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->label_sleep , &Button_home_start::signals_start , this , &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->label_getUp , &Button_home_start::signals_start , this , &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->clean_robot_button, &Button_home_start::signals_start, this, &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->router_button, &Button_home_start::signals_start, this, &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->curtain_button, &Button_home_start::signals_start, this, &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->fridge_button, &Button_home_start::signals_start, this, &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->air_button, &Button_home_start::signals_start, this, &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->light_button, &Button_home_start::signals_start, this, &Widget_funcC_Smart_Home::slots_button_start);
    connect(ui->play, &button_home_miusic::signals_start, this, [&](bool start){
        if (start)
        {
            ui->play->setPixmap(QPixmap(":/播放"));
            begin_play();
        }
        else
        {
            ui->play->setPixmap(QPixmap(":/停止"));
            stop_play();
        }
    });
    connect(ui->next_song, &button_home_miusic::signals_start, this, [&](bool start){
        Q_UNUSED (start);
        this->nextSong();
    });
    connect(ui->last_song, &button_home_miusic::signals_start, this, [&](bool start){
        Q_UNUSED (start);
        this->lastSong();
    });
    connect(ui->music_label, &button_home_miusic::signals_start, this, [&](bool start){
        Q_UNUSED (start);
        // 将此时的媒体播放传给弹窗
        this->find_miusic_dialog.setMediaPlayer(this->player);
        this->find_miusic_dialog.show();
    });

    // 连接弹窗发出的信号
    connect(&this->find_miusic_dialog, &dialog_home_find::search_sig, [&](QUrl search_url){
        set_url(search_url);
        get_search_json();
    });
    connect(&this->find_miusic_dialog, &dialog_home_find::next_song_sig, [&](){
        this->nextSong();
    });
    connect(&this->find_miusic_dialog, &dialog_home_find::last_song_sig, [&](){
        this->lastSong();
    });
    connect(&this->find_miusic_dialog, &dialog_home_find::play_song_sig, [&](){
        this->begin_play();
        this->ui->play->setPixmap(QPixmap(":/播放"));
        this->ui->play->set_start(true);
    });
    connect(&this->find_miusic_dialog, &dialog_home_find::stop_song_sig, [&](){
        this->stop_play();
        this->ui->play->setPixmap(QPixmap(":/停止"));
        this->ui->play->set_start(false);
    });
    connect(&this->find_miusic_dialog, &dialog_home_find::chang_mode_sig, [&](bool choice){
        if (choice)
        {
            this->index_play();
        }
        else
        {
            this->random_play();
        }
    });
}

// 初始化音乐进度条
void Widget_funcC_Smart_Home::init_music_bar()
{
    this->progressBar = new MusicProgressBar(this);
    progressBar->setMediaPlayer(this->player); // 关联播放器
    // 设置滑块图标（假设滑块资源为 ":/images/slider.png"）
    QPixmap slider_pixmap(":/滑块");
    slider_pixmap.scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    progressBar->setSliderPixmap(slider_pixmap);
    // 布局到左下角（示例：放在音乐动图下方，需调整布局）
    ui->music_layout->addWidget(progressBar);
}

// 随机播放
void Widget_funcC_Smart_Home::random_play()
{
    if (playlist.playbackMode() != QMediaPlaylist::Random)
    {
        playlist.setPlaybackMode(QMediaPlaylist::Random);
        player->setPlaylist(&this->playlist);
    }

}

// 顺序播放
void Widget_funcC_Smart_Home::index_play(void)
{
    if (this->playlist.playbackMode() != QMediaPlaylist::Sequential)
    {
        this->playlist.setPlaybackMode(QMediaPlaylist::Sequential); // 设置播放模式为顺序播放
        player->setPlaylist(&this->playlist);
    }
}

// 切换到下一首
void Widget_funcC_Smart_Home::nextSong()
{
    // 检查播放列表是否为空
    if (playlist.mediaCount() == 0)
    {
        return;
    }

    // 切歌前先停止当前播放，避免资源占用
    player->stop();
    cur_position = 0; // 重置进度
    // 如果顺序播放，播完最后一首歌，重头播放
    if (playlist.playbackMode() == QMediaPlaylist::Sequential && this->cur_index_song == this->song_information.size() - 1)
    {
        playlist.setCurrentIndex(0);
    }
    else
    {
        playlist.next(); // 切换到下一首
    }
    cur_index_song = playlist.currentIndex(); // 更新当前索引
    get_lyric_joson(); // 获取歌词JSON数据
    QStringList cur_song_information_list = this->analysis_song_information(cur_index_song); // 获取当前歌曲信息
    if (cur_song_information_list.isEmpty())
    {
        return;
    }
    this->ui->song_name->setText(cur_song_information_list.at(1)); // 显示歌名
    this->ui->singer_name->setText(cur_song_information_list.at(2)); // 显示歌手名
    // 延迟播放，给资源加载留时间
    QTimer::singleShot(200, this, [=]() {
        ui->play->setPixmap(QPixmap(":/播放"));
        ui->play->set_start(true);
        player->play();
    });
}

// 切换到上一首
void Widget_funcC_Smart_Home::lastSong()
{
    // 检查播放列表是否为空
    if (playlist.mediaCount() == 0)
    {
        return;
    }

    // 切歌前先停止当前播放，避免资源占用
    player->stop();
    cur_position = 0; // 重置进度

    if (playlist.playbackMode() == QMediaPlaylist::Sequential && cur_index_song == 0)
    {
        playlist.setCurrentIndex(0);
    }
    else
    {
       playlist.previous(); // 正常切换到上一首
    }
    cur_index_song = playlist.currentIndex(); // 更新当前索引
    get_lyric_joson(); // 获取歌词JSON数据
    QStringList cur_song_information_list = this->analysis_song_information(cur_index_song); // 获取当前歌曲信息
    if (cur_song_information_list.isEmpty())
    {
        return;
    }
    this->ui->song_name->setText(cur_song_information_list.at(1)); // 显示歌名
    this->ui->singer_name->setText(cur_song_information_list.at(2)); // 显示歌手名
    // 延迟播放，给资源加载留时间
    QTimer::singleShot(200, this, [=]() {
        ui->play->setPixmap(QPixmap(":/播放"));
        ui->play->set_start(true);
        player->play();
    });
}

// 初始化音乐动图
void Widget_funcC_Smart_Home::initGif()
{
    // 创建 QMovie 对象
    this->music_gif = new QMovie(":/音乐动图", "GIF", this);
    this->home_gif = new QMovie(":/家动图", "GIF", this);

    // 设置动图显示的 Label
    this->ui->music_gif->setMovie(this->music_gif);
    this->music_gif->start();
    this->music_gif->stop();
    this->ui->music_gif->setScaledContents(true); // 自适应 Label 大小
    this->ui->music_gif->resize(50, 50); // 设置 Label 尺寸

    this->ui->mp4_player_1->setMovie(this->home_gif);
    this->ui->mp4_player_1->setScaledContents(true); // 自适应 Label 大小

    this->home_gif->start();
}

// 向服务发送信息
void Widget_funcC_Smart_Home::send_message(QString message)
{
    this->client.send_msg(message);
}

// 用于返回歌曲的相关信息列表
QStringList Widget_funcC_Smart_Home::analysis_song_information(int index)
{
    if (index < 0 || index > this->song_information.size() - 1) // 索引有误返回空表
    {
        QMessageBox::warning(this,"提示","歌曲索引有误!", QMessageBox::Ok);
        return QStringList();
    }

    QString cur_song_information = this->song_information.at(index);
    QStringList cur_song_information_list = cur_song_information.split("&");
    return cur_song_information_list;
}

// 停止播放
void Widget_funcC_Smart_Home::stop_play()
{
    this->cur_position = player->position();
    this->player->stop();
}

// 开始播放音乐
void Widget_funcC_Smart_Home::begin_play()
{
    qDebug() << "恢复进度：" << cur_position; // 查看记录的进度是否正确
    if (this->cur_position != 0)
    {
        this->player->setPosition(this->cur_position);
    }
    this->player->play();
}

// 设置播放列表
void Widget_funcC_Smart_Home::set_playlist()
{
    playlist.clear();
    for (int i = 0; i < this->song_information.size(); i++)
    {
        QString cur_song_information = this->song_information.at(i);
        QStringList cur_song_list = cur_song_information.split("&");
        QString cur_song_id = cur_song_list.at(0);
        QString cur_song_url = QString("http://music.163.com/song/media/outer/url?id=") + cur_song_id + QString(".mp3");
        this->playlist.addMedia(QMediaContent(QUrl(cur_song_url)));
    }
    this->playlist.setPlaybackMode(QMediaPlaylist::Sequential); // 默认为顺序播放
    this->playlist.setCurrentIndex(0); // 默认播放列表中的第一首歌
    this->player->setPlaylist(&this->playlist); // 将播放列表添加到播放器
}

// 自定义槽函数
void Widget_funcC_Smart_Home::onReplied(QNetworkReply *reply)
{
    // 获取相应码
    int status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (reply->error() != QNetworkReply::NoError || status_code != 200)
    {
        QMessageBox::warning(this,"提示","请求数据失败!", QMessageBox::Ok);
    }
    else
    {
        QByteArray reply_data = reply->readAll();
        QByteArray byteArray = QString(reply_data).toUtf8();
        QFile file("./song.json");
        file.open(QFile::WriteOnly);
        file.write(byteArray);
        file.close();
    }
    reply->deleteLater();

    analysis_joson();
    // 重置当前歌曲索引
    this->cur_index_song = 0;
    // 设置当前歌单
    this->set_playlist();
    // 获取歌单中歌词的JSON数据
    this->get_lyric_joson();
    // 设置当前默认歌曲信息显示
    QString cur_song_information = this->song_information.at(cur_index_song); // 获取当前歌曲信息
    QStringList cur_song_information_list = cur_song_information.split("&"); // 解析当前歌曲信息
    this->ui->song_name->setText(cur_song_information_list.at(1)); // 显示歌名
    this->ui->singer_name->setText(cur_song_information_list.at(2)); // 显示歌手名

}

// 自定义槽函数
void Widget_funcC_Smart_Home::lyric_onReplied(QNetworkReply *reply)
{
    // 获取相应码
    int status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (reply->error() != QNetworkReply::NoError || status_code != 200)
    {
        QMessageBox::warning(this,"提示","请求数据失败!", QMessageBox::Ok);
    }
    else
    {
        QByteArray reply_data = reply->readAll();
        QByteArray byteArray = QString(reply_data).toUtf8();
        QFile file("./lyric.json");
        file.open(QFile::WriteOnly);
        file.write(byteArray);
        file.close();
    }
    reply->deleteLater();

    analysis_lyric_joson();
}

// 自定义槽函数
void Widget_funcC_Smart_Home::seach_onReplied(QNetworkReply *reply)
{
    // 清空之前的歌曲信息
    this->song_information.clear();
    this->playlist.clear();

    // 获取相应码
    int status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (reply->error() != QNetworkReply::NoError || status_code != 200)
    {
        QMessageBox::warning(this,"提示","请求数据失败!", QMessageBox::Ok);
    }
    else
    {
        QByteArray reply_data = reply->readAll();
        QByteArray byteArray = QString(reply_data).toUtf8();
        QFile file("./search.json");
        file.open(QFile::WriteOnly);
        file.write(byteArray);
        file.close();
    }
    reply->deleteLater();

    // 解析搜索JSON数据
    this->analysis_search_joson();

    // 获取歌单中歌词的JSON数据
    this->get_lyric_joson();
    // 设置当前默认歌曲信息显示
    QString cur_song_information = this->song_information.at(cur_index_song); // 获取当前歌曲信息
    QStringList cur_song_information_list = cur_song_information.split("&"); // 解析当前歌曲信息
    this->ui->song_name->setText(cur_song_information_list.at(1)); // 显示歌名
    this->ui->singer_name->setText(cur_song_information_list.at(2)); // 显示歌手名
}

// 歌词实时显示
void Widget_funcC_Smart_Home::onPositionChanged()
{
    if (this->cur_posi_list.isEmpty() || this->cur_lyric_list.isEmpty())
    {
        return;
    }

    // 使用二分查找法快速定位
    int left = 0;
    int right = this->cur_posi_list.size() - 1;
    int targetIndex = -1; // 目标对象索引

    while (left <= right)
    {
        int mid = (left + right) / 2;

        if (cur_posi_list.at(mid).toInt() <= this->player->position())
        {
            targetIndex = mid;
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }

    // 更新歌词显示（确保索引有效）
    if (targetIndex != -1 && targetIndex < cur_lyric_list.size())
    {
         ui->song_text->setText(cur_lyric_list[targetIndex]);
    }
}

// 自动切歌槽函数
void Widget_funcC_Smart_Home::onMediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    // 当媒体播放到末尾时（EndOfMedia 状态）
    if (status == QMediaPlayer::EndOfMedia)
    {
        this->nextSong();
    }
    if (this->player->state() == QMediaPlayer::PlayingState)
    {
        this->music_gif->start();
        this->ui->play->setPixmap(QPixmap(":/播放"));
        this->ui->play->set_start(true);
    }
    if (this->player->state() == QMediaPlayer::StoppedState)
    {
        this->music_gif->stop();
        this->ui->play->setPixmap(QPixmap(":/停止"));
        this->ui->play->set_start(false);
    }
}
